package ferp.android.social.twvk.vk;

import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import com.perm.kate.api.Api;
import com.perm.kate.api.KException;
import ferp.android.R;
import ferp.android.dialogs.ShareDialog;
import ferp.android.social.Post;
import ferp.android.social.twvk.Account;
import ferp.android.social.twvk.TwVkConnector;
import ferp.core.game.Settings;
import ferp.core.log.Log;

import java.util.LinkedList;
import java.util.List;

/**
 * User: olegs
 * Date: 5/11/13 12:32 AM
 */
public class VkConnector extends TwVkConnector
{
  static final String TAG = Log.TAG + "/Vk";

  @Override
  public int getRequestCode()
  {
    return RequestCode.VK;
  }

  @Override
  public ImageView getLogoutIcon(ShareDialog dialog)
  {
    return (ImageView)(dialog.findViewById(R.id.social_frame_layout_vk).findViewById(R.id.dlg_share_logout));
  }

  @Override
  public ImageView getProgressIcon(ShareDialog dialog)
  {
    return (ImageView)(dialog.findViewById(R.id.social_frame_layout_vk).findViewById(R.id.dlg_share_clock));
  }

  @Override
  public ImageView getPostToastIcon(View toast)
  {
    return (ImageView)toast.findViewById(R.id.toast_post_result_vk);
  }

  @Override
  public ImageView getLogoutToastIcon(View toast)
  {
    return (ImageView)toast.findViewById(R.id.toast_social_logout_vk);
  }

  @Override
  protected void doLogin(Activity owner, int requestCode)
  {
    api = null;

    super.doLogin(owner, requestCode);
  }

  @Override
  protected Class getLoginActivityClass()
  {
    return VkLoginActivity.class;
  }

  @Override
  protected PostError publish(Activity owner, Post post)
  {
    try
    {
      Account a = loadAccount(owner);

      if (api == null)
        api = new Api(a.accessToken, API_ID);

      long postID = api.createWallPost(a.secretAsLong(), post.getText(owner.getResources().getString(R.string.post_playing_in_preferans)),
                                       attachments, null, false, false, false, null, null, null, 0L, null, null);

      Log.debug(TAG, "Publish succeeded, postID: " + postID);

      return null;
    }
    catch (KException e)
    {
      Log.debug(TAG, "Publish failed, error code: " + e.error_code);
      return new PostError(-1, e.getMessage());
    }
    catch (Exception e)
    {
      Log.error(TAG, e);
      return new PostError(-2, e.getMessage());
    }
  }

  @Override
  protected void doLogout(Activity owner)
  {
    api = null;
  }

  static final String API_ID = "3635753";

  private static final String ATTACHMENTS = Post.link(Settings.Locale.RUSSIAN) + ",photo210957605_303121653";
  private static final List<String> attachments = new LinkedList<String>();

  private Api api;

  static
  {
    attachments.add(ATTACHMENTS);
  }
}
